package me.caofeng.pojo;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import me.caofeng.enums.ResponseCode;
import me.caofeng.util.JsonUtil;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.awt.*;
import java.io.IOException;
import java.io.Writer;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.pojo
 * @Description:
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-16 10:42
 * @Version: V1.0
 */
//@XmlRootElement(name = "response")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Response<T> {
    private int status;
    private String message;
    private T data;

    private Response() {
    }

    @JsonIgnore
    public boolean isSuccess() {
        return this.status == ResponseCode.SUCCESS.getCode();
    }

    public int getStatus() {
        return status;
    }

    public String getMessage() {
        return message;
    }

    public T getData() {
        return data;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setData(T data) {
        this.data = data;
    }

    public static <T> Response<T> response(ResponseCode code, String message, T data) {
        Response<T> response = new Response<T>();
        if (null != code) {
            response.setStatus(code.getCode());
        }

        if (null != message) {
            response.setMessage(message);
        }

        if (null != data) {
            response.setData(data);
        }
        return response;
    }

    public static <T> void response(ResponseCode code, HttpServletResponse servletResponse, String message, T data) throws IOException {
        servletResponse.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        Response response = Response.response(code, message, data);
        String json = JsonUtil.toJSon(response);
        Writer writer = servletResponse.getWriter();
        writer.write(json);
        writer.flush();
    }

    @Override
    public String toString() {
        return "Response{" +
                "status=" + status +
                ", message='" + message + '\'' +
                ", data=" + data +
                '}';
    }
}
